package com.yue.springDemo.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yue.springDemo.business.bean.User;
import com.yue.springDemo.business.mapper.HelloMapper;
import com.yue.springDemo.framework.bean.TheUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service("theUserDetailsService")
public class TheUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private HelloMapper helloMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 构建用户信息的逻辑
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("job_number", username);
        User user = helloMapper.selectOne(wrapper);
        if (user == null) {
            throw new UsernameNotFoundException("该工号不存在");
        }

        TheUserDetails userInfo = new TheUserDetails();
        userInfo.setUsername(user.getJobNumber());
        userInfo.setPassword(user.getPassword());

        Set<GrantedAuthority> authoritiesSet = new HashSet<>();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");
        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;
    }
}
